package pers.w.chaptertalk.ui.me;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

import pers.w.chaptertalk.MainActivity;
import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.IReader;
import pers.w.chaptertalk.funs.ISetting;
import pers.w.chaptertalk.ui.login.LoginActivity;

public class MeFragment extends Fragment implements View.OnClickListener, ISetting, IReader {

    private MeViewModel meViewModel;
    private MainActivity activity;

    private TextView tv_talker;
    private Handler handler = new Handler(msg -> {

        switch (msg.what) {
            case HANDLER_UP_BOOKRACK:
                break;
            case HANDLER_DOWN_BOOKRACK_PROGRESS:
                activity.showMsg((String) msg.obj);
                break;
            case HANDLER_TOAST:
                Toast.makeText(activity, (String)msg.obj, Toast.LENGTH_SHORT).show();
                break;
            case HANDLER_DOWN_BOOKRACK_FINISH:
                activity.hideLoading();
                activity.getBooksFragment().updateAdapter();
                if (msg.obj!=null)
                    Toast.makeText(activity, (String)msg.obj, Toast.LENGTH_SHORT).show();
                break;
            case HANDLER_CHECK_VERSION:
                AlertDialog dialog = new AlertDialog.Builder(activity)
                        .setTitle("更新")
                        .setPositiveButton("朕知道了", null)
                        .create();
                if (msg.arg1 == 1) {
                    dialog.setMessage("有更新，点击书架上方的公告，有下载地址，请谅解。");
                } else if (msg.arg1 == -1) {
                    dialog.setMessage(getString(R.string.server_error));
                } else
                    dialog.setMessage("已经是最新版");

                dialog.show();
                break;
        }
        return false;
    });

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        meViewModel =new
                ViewModelProvider(this).get(MeViewModel.class);
        final View root = inflater.inflate(R.layout.fragment_me, container, false);

        meViewModel.setContent(getContext());

        ImageView iv_talker = root.findViewById(R.id.iv_talker);
        iv_talker.setOnClickListener(this);

        Button btn;
        int[] btnIDs = new int[]{
                R.id.btn_cache_manager,
                R.id.btn_about,
                R.id.btn_feedback,
                R.id.btn_up_bookrack,
                R.id.btn_download_bookrack,
                R.id.btn_update};
        for (int id : btnIDs) {
            btn = root.findViewById(id);
            btn.setOnClickListener(this);
        }
        tv_talker = root.findViewById(R.id.tv_talker);
        tv_talker.setText("点击头像登录");
        load_setting();

        meViewModel.getText().observe(getViewLifecycleOwner(), text -> {
            Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
            activity.hideLoading();
        });
        assert getActivity() != null;
        activity = (MainActivity) getActivity();
        books = activity.getBooksFragment().getBooks();
        return root;

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        final String bookrackURI = getString(R.string.server_address) + "bookrack.php";
        AlertDialog dialog;
        switch (v.getId()) {
            case R.id.iv_talker:
                intent = new Intent(getContext(), LoginActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.btn_cache_manager:
                intent = new Intent(getContext(), LookCacheActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_about:
                intent = new Intent(getContext(), AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_feedback://建议反馈，留言
                if (Fun.isNetworkConnected(getContext())) {
                    intent = new Intent(getContext(), LeaveMessageActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.btn_up_bookrack:
                if (Fun.isNetworkConnected(getContext()) && Fun.hasAccount(getContext())) {
                    dialog = new AlertDialog.Builder(getActivity())
                            .setMessage("你确定要上传吗？这将覆盖服务器数据。")
                            .setTitle("上传书架")
                            .setPositiveButton("朕确定", (dialog1, which) ->
                                    meViewModel.up_down_bookrack(handler, books, bookrackURI, true))
                            .setNegativeButton("取消", null)
                            .create();
                    dialog.show();
                }
                break;
            case R.id.btn_download_bookrack:
                if (Fun.isNetworkConnected(getContext()) && Fun.hasAccount(getContext())) {
                    dialog = new AlertDialog.Builder(getActivity())
                            .setMessage("你确定要下载吗？这将耗时较长，期间不要进行其他操作。\n" +
                                    "不会丢失本地书架中的书籍，只是添加本地没有的书籍。\n" +
                                    "但是！已有书籍会更新书籍的本地阅读进度。")
                            .setTitle("下载书架")
                            .setPositiveButton("朕确定", (dialog1, which) -> {
                                activity.showLoading();
                                meViewModel.up_down_bookrack(handler, books, bookrackURI, false);
                            })
                            .setNegativeButton("取消", null)
                            .create();
                    dialog.show();
                }
                break;
            case R.id.btn_update:
                if (Fun.isNetworkConnected(getContext())) {
                    final String versionUri = getString(R.string.server_address) + "version.php";
                    meViewModel.checkVersion(versionUri, handler);

                }
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            tv_talker.setText((String) Fun.SHARE_MAP.get(R.string.prompt_username));
            tv_talker.setTextColor(Color.BLUE);
            save_setting();
        }
    }


    @Override
    public void load_setting() {//已经在activity中先load了
        //Properties properties = new Properties();
        String u = (String) Fun.SHARE_MAP.get(R.string.prompt_username);
        String p = (String) Fun.SHARE_MAP.get(R.string.prompt_password);
        if (u != null && p != null) {
            if (u.length() >= 3) {
                tv_talker.setText(u);
                tv_talker.setTextColor(Color.BLUE);
                Fun.SHARE_MAP.put(R.string.prompt_username, u);
            }

        }
    }

    public static final String CONFIG_NAME = "TALK";

    @Override
    public void save_setting() {
        Properties properties = new Properties();

        String u = (String) Fun.SHARE_MAP.get(R.string.prompt_username);
        String p = (String) Fun.SHARE_MAP.get(R.string.prompt_password);
        if (u != null && p != null && u.length() >= 3) {
            try {
                OutputStream out = Objects.requireNonNull(getContext()).openFileOutput(CONFIG_NAME, Context.MODE_PRIVATE);

                properties.setProperty(USER, u);
                properties.setProperty(PASSWORD, p);
                properties.store(out, null);
                out.close();
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }

        if (Fun.isDebug()) Log.d("config" + CONFIG_NAME, "save_setting: ");

    }

    private List<BookInfo> books;

//    public void setBooks(List<BookInfo> books) {
//        this.books = books;
//    }
}
